/**
 * ReportGear(2011)
 */
package com.reportgear.report.view.grid;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;

import javax.swing.event.MouseInputAdapter;

import com.reportgear.report.view.JWorksheet;
import com.reportgear.report.view.cursor.CursorUtils;
import com.reportgear.report.view.grid.selection.GridSelection;
import com.reportgear.report.view.grid.util.GraphHelper;

/**
 * Grid左上角控件
 * 
 * @version 1.0 2011-3-14
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 * 
 */
public class GridCornor extends BaseGridComponent {
	/**
	 * UID
	 */
	private static final long serialVersionUID = -4170652021717508195L;

	/**
	 * Grid左上角鼠标动作处理
	 */
	private class GridCornerMouseHandler extends MouseInputAdapter {

		/**
		 * 选择所有单元格
		 */
		private void doSelectAll() {
			final GridSelection gridSelection = worksheet.getGridSelection();
			gridSelection.setType(GridSelection.Type.CELL);
			gridSelection.setEditBounds(0, 0, 1, 1);
			gridSelection.setOnlySelection(0, 0, worksheet.getColumnCount(), worksheet.getRowCount());

			worksheet.refresh();
			worksheet.fireGridSelectionChanged();
		}

		@Override
		public void mouseClicked(MouseEvent evt) {
			if (!(isEnabled())) {
				return;
			}
			this.doSelectAll();
		}

		@Override
		public void mouseMoved(MouseEvent mouseEvent) {
			if (!(isEnabled())) {
				return;
			}

			setCursor(CursorUtils.CURSOR_DEFAULT);
		}
	}

	public GridCornor(JWorksheet worksheet) {
		super(worksheet);

		this.setOpaque(true);
		 GridCornerMouseHandler mouseHandler = new GridCornerMouseHandler();
		this.addMouseListener(mouseHandler);
		this.addMouseMotionListener(mouseHandler);
		this.getInputMap().clear();
		this.getActionMap().clear();
	}

	@Override
	public Dimension getPreferredSize() {
		if (!this.worksheet.isColumnHeaderVisible() || !this.worksheet.isRowHeaderVisible()) {
			return new Dimension(0, 0);
		}

		return new Dimension(this.worksheet.getGridRowHeader().getWidth(), this.worksheet.getGridColumnHeader()
				.getHeight());
	}

	@Override
	public void paintComponent(Graphics g) {
		final Graphics2D g2 = (Graphics2D) g;
		final Dimension dim = this.getSize();
		final Rectangle2D client = new Rectangle2D.Double(0.0D, 0.0D, dim.getWidth(), dim.getHeight());

		g2.setPaint(this.getBackground());
		GraphHelper.fill(g2, client);
		g2.setColor(this.worksheet.getGridColumnHeader().getSeparatorLineColor());
		GraphHelper.drawLine(g2, 0.0D, 0.0D, 0.0D, dim.getHeight());
		g2.setColor(this.worksheet.getGridRowHeader().getSeparatorLineColor());
		GraphHelper.drawLine(g2, 0.0D, 0.0D, dim.getWidth(), 0.0D);
	}
}
